package com.ng.common.component.engine.parser;

import java.util.Collections;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

import org.apache.commons.lang3.StringUtils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

/**
 * 流程解析器
 * 用于处理JSON数据的遍历和转换操作
 */
public final class FlowParser {
	
	private static final String FOR_OPERATION = "for";
	private static final String ITERATOR_OPERATION = "iterator";
	private static final String VALUE_TYPE = "value";
	private static final String KEY_TYPE = "key";
	
	/**
	 * 私有构造函数，防止实例化
	 */
	private FlowParser() {
		throw new UnsupportedOperationException("Utility class cannot be instantiated");
	}
	
	/**
	 * 执行流程解析
	 * 
	 * @param operation 操作类型（for/iterator）
	 * @param inputValue 输入值
	 * @param returnType 返回类型（value/key）
	 * @return 处理后的JSONArray
	 * @throws IllegalArgumentException 当参数无效时
	 */
	public static JSONArray exec(String operation, Object inputValue, String returnType) {
		// 参数校验
		validateParameters(operation, inputValue, returnType);
		
		// 处理for操作
		if (FOR_OPERATION.equalsIgnoreCase(operation)) {
			return handleForOperation(inputValue);
		}
		
		// 处理iterator操作
		if (ITERATOR_OPERATION.equalsIgnoreCase(operation)) {
			return handleIteratorOperation(inputValue, returnType);
		}
		
		return new JSONArray();
	}
	
	/**
	 * 处理for操作
	 */
	private static JSONArray handleForOperation(Object inputValue) {
		if (!(inputValue instanceof JSONArray)) {
			throw new IllegalArgumentException("For operation requires JSONArray input");
		}
		return (JSONArray) inputValue;
	}
	
	/**
	 * 处理iterator操作
	 */
	private static JSONArray handleIteratorOperation(Object inputValue, String returnType) {
		if (!(inputValue instanceof JSONObject)) {
			throw new IllegalArgumentException("Iterator operation requires JSONObject input");
		}
		
		JSONObject jsonObject = (JSONObject) inputValue;
		
		// 使用Stream API处理集合
		if (VALUE_TYPE.equalsIgnoreCase(returnType)) {
			return new JSONArray(
				jsonObject.values()
					.stream()
					.filter(Objects::nonNull)
					.collect(Collectors.toList())
			);
		}
		
		if (KEY_TYPE.equalsIgnoreCase(returnType)) {
			return new JSONArray(
				jsonObject.keySet()
					.stream()
					.filter(StringUtils::isNotEmpty)
					.collect(Collectors.toList())
			);
		}
		
		return new JSONArray();
	}
	
	/**
	 * 参数验证
	 */
	private static void validateParameters(String operation, Object inputValue, String returnType) {
		if (StringUtils.isEmpty(operation)) {
			throw new IllegalArgumentException("Operation cannot be empty");
		}
		
		if (inputValue == null) {
			throw new IllegalArgumentException("Input value cannot be null");
		}
		
		if (!isValidOperation(operation)) {
			throw new IllegalArgumentException("Invalid operation: " + operation);
		}
		
		if (ITERATOR_OPERATION.equalsIgnoreCase(operation) && !isValidReturnType(returnType)) {
			throw new IllegalArgumentException("Invalid return type for iterator operation: " + returnType);
		}
	}
	
	/**
	 * 检查操作类型是否有效
	 */
	private static boolean isValidOperation(String operation) {
		return FOR_OPERATION.equalsIgnoreCase(operation) || 
			   ITERATOR_OPERATION.equalsIgnoreCase(operation);
	}
	
	/**
	 * 检查返回类型是否有效
	 */
	private static boolean isValidReturnType(String returnType) {
		return VALUE_TYPE.equalsIgnoreCase(returnType) || 
			   KEY_TYPE.equalsIgnoreCase(returnType);
	}
	
	/**
	 * 安全地获取JSONObject的值
	 */
	public static Optional<Object> safeGetValue(JSONObject jsonObject, String key) {
		return Optional.ofNullable(jsonObject)
			.map(obj -> obj.get(key));
	}
	
	/**
	 * 安全地获取JSONArray的元素
	 */
	public static Optional<Object> safeGetElement(JSONArray jsonArray, int index) {
		return Optional.ofNullable(jsonArray)
			.filter(arr -> index >= 0 && index < arr.size())
			.map(arr -> arr.get(index));
	}
	
	/**
	 * 将JSONObject转换为Map
	 */
	public static Map<String, Object> toMap(JSONObject jsonObject) {
		return Optional.ofNullable(jsonObject)
			.map(obj -> obj.entrySet().stream()
				.collect(Collectors.toMap(
					Map.Entry::getKey,
					Map.Entry::getValue,
					(v1, v2) -> v2)))
			.orElse(Collections.emptyMap());
	}
	
	public static void main(String[] args) {
		// 处理JSONArray
		JSONArray array = new JSONArray();
		array.add("item1");
		array.add("item2");
		JSONArray result1 = FlowParser.exec("for", array, null);
		
		System.out.println(result1);

		// 处理JSONObject的值
		JSONObject object = new JSONObject();
		object.put("key1", "value1");
		object.put("key2", "value2");
		JSONArray result2 = FlowParser.exec("iterator", object, "value");
		System.out.println(result2);

		// 处理JSONObject的键
		JSONArray result3 = FlowParser.exec("iterator", object, "key");
		System.out.println(result3);

		// 安全访问
		Optional<Object> value = FlowParser.safeGetValue(object, "key1");
		Map<String, Object> map = FlowParser.toMap(object);
		
		System.out.println(value);
		System.out.println(map);
	}
}
